package com.gitee.liuzhi.framework.starter.swagger.config;

import com.gitee.liuzhi.framework.starter.swagger.properties.SwaggerProperties;
import com.google.common.collect.Sets;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.boot.SpringBootVersion;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import javax.annotation.Nonnull;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;

/**
 * Created by 2022/5/9/0009
 *
 * @author LiuZhi
 * @version V1.0
 * @description: SwaggerConfiguration
 */
@Slf4j
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfiguration implements WebMvcConfigurer {

    private final SwaggerProperties swaggerProperties;

    public SwaggerConfiguration(SwaggerProperties swaggerProperties) {
        this.swaggerProperties = swaggerProperties;
    }

    @Bean
    public Docket createRestApi() {
        log.info(String.format("swagger properties info. %s", swaggerProperties.toString()));
        return new Docket(DocumentationType.OAS_30).pathMapping(swaggerProperties.getBasePath())
                // 定义是否开启swagger, false为关闭, 可以通过变量控制
                .enable(swaggerProperties.getEnable())
                // 将 api 的元信息设置为包含在 json ResourceListing 响应中
                .apiInfo(apiInfo())
                // 接口调试地址
                .host(swaggerProperties.getTryHost())
                // 选择哪些接口作为swagger的doc发布
                .select()
                    // 扫描全部
                    .apis(RequestHandlerSelectors.any())
                    // 都不扫描
                    // .apis(RequestHandlerSelectors.none())
                    .paths(PathSelectors.any())
                    // 按照包路径扫描
                    .apis(RequestHandlerSelectors.basePackage(swaggerProperties.getBasePackage()))
                    // 按照类注解扫描
                    //.apis(RequestHandlerSelectors.withClassAnnotation(RestController.class))
                    // 按照方法注解扫描
                    // .apis(RequestHandlerSelectors.withMethodAnnotation(GetMapping.class))
                .build()
                // 支持的通讯协议集合
                .protocols(Sets.newHashSet("https", "http"));
        // 授权信息全局应用
        // .securityContexts(securityContexts())
        // .securitySchemes(Arrays.asList(securityScheme()));
    }

    /**
     * 在文档页面中展示的api基本信息
     *
     * @return http://project-location/swagger-ui.html
     */
    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title(swaggerProperties.getApplicationName() + " Api Doc")
                .description(swaggerProperties.getApplicationDescription())
                .version("Application Version: " + swaggerProperties.getApplicationVersion() + ", Spring Boot Version: " + SpringBootVersion.getVersion())
                .contact(new Contact(swaggerProperties.getContactName(), swaggerProperties.getContactUrl(), swaggerProperties.getContactEmail()))
                .build();
    }

    /**
     * 授权信息全局应用
     */
    private List<SecurityContext> securityContexts() {
        return Collections.singletonList(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .build()
        );
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    private SecurityScheme securityScheme() {
        return new ApiKey("Authorization", "Authorization", "header");
    }

    /**
     * 通用拦截器排除swagger设置，所有拦截器都会自动加swagger相关的资源排除信息
     */
    @SuppressWarnings("unchecked")
    @Override
    public void addInterceptors(@Nonnull InterceptorRegistry registry) {
        try {
            Field registrationsField = FieldUtils.getField(InterceptorRegistry.class, "registrations", true);
            List<InterceptorRegistration> registrations = (List<InterceptorRegistration>) ReflectionUtils.getField(registrationsField, registry);
            if (Objects.nonNull(registrations)) {
                for (InterceptorRegistration interceptorRegistration : registrations) {
                    interceptorRegistration
                            .excludePathPatterns("/swagger**/**")
                            .excludePathPatterns("/webjars/**")
                            .excludePathPatterns("/v3/**")
                            .excludePathPatterns("/doc.html");
                }
            }
        } catch (Exception e) {
            log.error(String.format("addInterceptors fail. message : %s", e.getMessage()), e);
        }
    }

}
